﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using System.Threading;
using System.Web.Security;
using System.Windows.Forms;
using RedRain.Collaborate.Contract.Models;
using RRSimulator.BlobManager.AuthenticationService;
using RRSimulator.BlobManager.Lib;

namespace RRSimulator.BlobManager
{
    public class Program
    {
        public static void Main(string[] args)
        {
            InitAzureConnection();
            //HostService();
            //BlobManagerClient serviceClient = new BlobManagerClient();

            //string containerName = "testblobcontainer";
            //string fileName = @"Data\2yivijjj.znt";//"TextDocument.txt";

            //FileStream fs = File.OpenRead(fileName);
            //UploadFileStreamRequest request = new UploadFileStreamRequest();
            //request.BlobName = fileName;
            //request.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            //request.ContrainerName = containerName;
            //request.HashValue = HashFile(fs);
            //request.FileStream = fs;
            ////request.FileBytes = new byte[fs.Length];
            ////fs.Read(request.FileBytes, 0, (int)fs.Length);
            ////fs.Close();

            ////serviceClient.UploadFileCompleted += serviceClient_UploadFileCompleted;
            ////serviceClient.UploadFileAsync(request, "This is user state.");
            ////var responseAsync = serviceClient.UploadFile(request);
            //serviceClient.UploadFileStreamCompleted += serviceClient_UploadFileStreamCompleted;
            //serviceClient.UploadFileStreamAsync(request, "This is user state.");
            //System.Console.ReadLine();

            //AuthenticationServiceClient authClient = new AuthenticationServiceClient();
            //using (new OperationContextScope(authClient.InnerChannel))
            //{
            //    bool result = authClient.Login("afisher", "@accel4me", string.Empty, true);
            //    var responseMessageProperty = (HttpResponseMessageProperty)
            //         OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name];

            //    if (result)
            //    {
            //        string cookie = responseMessageProperty.Headers.Get("Set-Cookie");
            //        Console.WriteLine(result.ToString() + Environment.NewLine + cookie);
            //        Globals.Cookie = cookie;
            //    }
            //}

            //BlobManagerClient client = new BlobManagerClient();
            //var testString = client.TestOperation(new Lib.ServiceClient.TestOperationRequest { BlobName = "Siapa", ContainerName = "Akuwh", TestString = "Siapa akuwh?" });

            //IBlobManagerRunner blobManagerRunner = new BlobManagerRunner("testblobcontainer", OperationMode.Sync, UploadDataMode.Bytes);
            
            //blobManagerRunner.LoadFiles(Directory.GetFiles(@"Data\"));

            //(blobManagerRunner as BlobManagerRunner).ProcessCompleted += Program_ProcessCompleted;
            //(blobManagerRunner as BlobManagerRunner).StartStopwatch();
            //blobManagerRunner.UploadFiles();
            //(blobManagerRunner as BlobManagerRunner).StopStopwatch();
            //blobManagerRunner.UploadFile("File - 01.znt");
            //blobManagerRunner.DeleteBlob("hlbqsli2.2en");
            System.Console.ReadLine();
        }

        private static void InitAzureConnection()
        {
            // "net.tcp://redraindev.cloudapp.net:10001/AuthorizedUserService";
            string serviceUrl = @"net.tcp://127.255.0.1:11001/AuthorizedUserService";

            EndpointAddress endpointAddress = new EndpointAddress(serviceUrl);
            NetTcpBinding binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;
            binding.Security.Message.ClientCredentialType = MessageCredentialType.None;

            // binding = new NetTcpBinding(SecurityMode.None);
            //ChannelFactory<IAuthorizedUserService> channelFactory = new ChannelFactory<IAuthorizedUserService>(binding, endpointAddress);
            //channelFactory.Endpoint.EndpointBehaviors.Add(new InterceptorBehaviorExtension());
            //IAuthorizedUserService authorizedUserChannel = channelFactory.CreateChannel();

            using (AuthorizedUserServiceClient clientService = new AuthorizedUserServiceClient(binding, endpointAddress))
            using (new OperationContextScope(clientService.InnerChannel))
            {
                //clientService.Endpoint.EndpointBehaviors.Add(new InterceptorBehaviorExtension());
                
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    "afisher@redraincorp.com",
                    DateTime.Now,
                    DateTime.Now.AddSeconds(5),
                    true,
                    "Administrator",
                    FormsAuthentication.FormsCookiePath);

                try
                {
                    LoginRequest request = new LoginRequest() { TenantId = "tenantnewredview", Username = "afisher@redraincorp.com", Password = "@accel4me" };
                    var meh = clientService.Login(request); //authorizedUserChannel.Login(new LoginRequest { TenantId = "tenantnewredview", Username = "afisher@redraincorp.com", Password = "@accel4me" }); var responseMessageProperty = (HttpResponseMessageProperty)
                    Thread.Sleep(15000);
                    var meh2 = clientService.TestOperation(FormsAuthentication.Encrypt(ticket));
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        private static void InitAzureConnection2()
        {
            // "net.tcp://redraindev.cloudapp.net:10001/AuthorizedUserService";
            string serviceUrl = @"net.tcp://127.255.0.1:11001/AuthorizedUserService";

            EndpointAddress endpointAddress = new EndpointAddress(serviceUrl);
            NetTcpBinding binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;
            binding.Security.Message.ClientCredentialType = MessageCredentialType.None;

            // binding = new NetTcpBinding(SecurityMode.None);
            //ChannelFactory<IAuthorizedUserService> channelFactory = new ChannelFactory<IAuthorizedUserService>(binding, endpointAddress);
            //channelFactory.Endpoint.EndpointBehaviors.Add(new InterceptorBehaviorExtension());
            //IAuthorizedUserService authorizedUserChannel = channelFactory.CreateChannel();

            using (AuthorizedUserServiceClient clientService = new AuthorizedUserServiceClient())
            using (new OperationContextScope(clientService.InnerChannel))
            {
                //clientService.Endpoint.EndpointBehaviors.Add(new InterceptorBehaviorExtension());

                try
                {
                    LoginRequest request = new LoginRequest() { TenantId = "tenantnewredview", Username = "afisher@redraincorp.com", Password = "@accel4me" };
                    var meh = clientService.Login(request); //authorizedUserChannel.Login(new LoginRequest { TenantId = "tenantnewredview", Username = "afisher@redraincorp.com", Password = "@accel4me" }); var responseMessageProperty = (HttpResponseMessageProperty)
                    var responseMessageProperty = (HttpResponseMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name];

                    if (!meh.IsError)
                    {
                        string cookie = responseMessageProperty.Headers.Get("Set-Cookie");
                        Console.WriteLine(Environment.NewLine + cookie);
                        Globals.Cookie = cookie;
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        private static void HostService()
        {
            // Create a ServiceHost for the CalculatorService type.
            using (ServiceHost serviceHost = new ServiceHost(typeof(AuthorizedUserServiceClient)))
            {
                ServiceMetadataBehavior smb = 
                        serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
                if (smb == null) serviceHost.Description.Behaviors.Add(
                                   new ServiceMetadataBehavior());
                serviceHost.AddServiceEndpoint(typeof(IMetadataExchange),
                                 MetadataExchangeBindings.CreateMexTcpBinding(), @"net.tcp://localhost:9006/servicemodelsamples/service");
                serviceHost.AddServiceEndpoint(typeof(IAuthorizedUserService), 
                                               new NetTcpBinding(), @"net.tcp://localhost:9005/servicemodelsamples/service");
                // Open the ServiceHost to create listeners
                    //  and start listening for messages.
                serviceHost.Open();

                // The service can now be accessed.
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();
            }
        }

        static void Program_ProcessCompleted(object sender, string ElapsedTime)
        {
            System.Console.WriteLine();
            System.Console.WriteLine();
            System.Console.WriteLine("Overall process time : {0}", ElapsedTime);
        }
    }
}
